package com.smart.campus.web.controller.school;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.smart.campus.common.utils.DateUtils;
import com.smart.campus.framework.util.ShiroUtils;
import com.smart.campus.school.domain.AdjustCourseAdmin;
import com.smart.campus.school.domain.ClassInfo;
import com.smart.campus.school.domain.Grade;
import com.smart.campus.school.domain.query.IllegalRecordQuery;
import com.smart.campus.school.domain.vo.IllegalRecordReportVo;
import com.smart.campus.school.service.*;
import com.smart.campus.system.domain.SysUser;
import com.smart.campus.web.utils.SchoolUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.smart.campus.common.annotation.Log;
import com.smart.campus.common.enums.BusinessType;
import com.smart.campus.school.domain.AdjustCourse;
import com.smart.campus.common.core.controller.BaseController;
import com.smart.campus.common.core.domain.AjaxResult;
import com.smart.campus.common.utils.poi.ExcelUtil;
import com.smart.campus.common.core.page.TableDataInfo;

import static com.smart.campus.common.utils.DateUtils.YYYY_MM_DD_HH_MM_SS;

/**
 * 调课Controller
 * 
 * @author Zhihe.Li
 * @date 2020-08-15
 */
@Controller
@RequestMapping("/school/course")
public class AdjustCourseController extends BaseController
{
    private String prefix = "school/course";

    @Autowired
    private IAdjustCourseService adjustCourseService;

    @Autowired
    private IApplyListService applyListService;
    @Autowired
    private IAdjustCourseAdminService adjustCourseAdminService;


    @Autowired
    private IClassInfoService classInfoService;

    @Autowired
    private IGradeService gradeService;

    @RequiresPermissions("school:course:view")
    @GetMapping()
    public String course()
    {
        return prefix + "/course";
    }

    /**
     * 查询调课列表
     */
    @RequiresPermissions("school:course:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AdjustCourse adjustCourse)
    {
        startPage();
        AdjustCourseAdmin admin = new AdjustCourseAdmin();
        admin.setAdminIds(String.valueOf(ShiroUtils.getUserId()));
        List<AdjustCourseAdmin> adminList = adjustCourseAdminService.selectAdjustCourseAdminList(admin);
        if(CollectionUtils.isEmpty(adminList)){
            //如果当前操作人不是调课管理员 那么只能看到自己的数据
            adjustCourse.setTeacherId(ShiroUtils.getUserId());
        }
        List<AdjustCourse> list = adjustCourseService.selectAdjustCourseList(adjustCourse);
        return getDataTable(list);
    }

    /**
     * 导出调课列表
     */
    @RequiresPermissions("school:course:export")
    @Log(title = "调课", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(AdjustCourse adjustCourse)
    {
        List<AdjustCourse> list = adjustCourseService.selectAdjustCourseList(adjustCourse);
        ExcelUtil<AdjustCourse> util = new ExcelUtil<AdjustCourse>(AdjustCourse.class);
        return util.exportExcel(list, "course");
    }

    /**
     * 新增调课
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {

        // 取身份信息
        SysUser user = ShiroUtils.getSysUser();
        mmap.put("user",user);
        return prefix + "/add";
    }

    /**
     * 新增保存调课
     */
    @RequiresPermissions("school:course:add")
    @Log(title = "调课", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(AdjustCourse adjustCourse)
    {
        adjustCourse.setSchoolId(SchoolUtil.getSchoolId());
        return toAjax(adjustCourseService.insertAdjustCourse(adjustCourse));
    }

    /**
     * 修改调课
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        AdjustCourse adjustCourse = adjustCourseService.selectAdjustCourseById(id);
        mmap.put("adjustCourse", adjustCourse);
        return prefix + "/edit";
    }

    /**
     * 修改保存调课
     */
    @RequiresPermissions("school:course:edit")
    @Log(title = "调课", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(AdjustCourse adjustCourse)
    {
        return toAjax(adjustCourseService.updateAdjustCourse(adjustCourse));
    }

    /**
     * 删除调课
     */
    @RequiresPermissions("school:course:remove")
    @Log(title = "调课", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(adjustCourseService.deleteAdjustCourseByIds(ids));
    }



    @RequiresPermissions("school:course:approve")
    @GetMapping("/approve")
    public String courseApprove()
    {
        return prefix + "/approveList";
    }

    /**
     * 查询调课列表
     */
    @PostMapping("/approveList")
    @ResponseBody
    public TableDataInfo approveList(AdjustCourse adjustCourse)
    {
        startPage();

        adjustCourse.setApproverIds(ShiroUtils.getUserId().toString());
        List<AdjustCourse> list = adjustCourseService.selectAdjustCourseListByUserId(ShiroUtils.getUserId());
        return getDataTable(list);
    }

    /**
     * 设置代课老师
     */
    @GetMapping("/setTeacher/{id}")
    public String setTeacher(@PathVariable("id") Long id, ModelMap mmap)
    {
        AdjustCourse adjustCourse = adjustCourseService.selectAdjustCourseById(id);
        mmap.put("adjustCourse", adjustCourse);
        return prefix + "/approve";
    }
    /**
     * 查询违规记录报表
     */
    @PostMapping("/getReport")
    @ResponseBody
    public List<Map<String,Object>> getReport(AdjustCourse query)
    {

        List<Map<String,Object>> mapList = new ArrayList<>();
        Grade gradeParam = new Grade();
        gradeParam.setShcoolId(SchoolUtil.getSchoolId());
        List<Grade> gradeList = gradeService.selectGradeList(gradeParam);

        for (Grade grade : gradeList) {
            Map<String,Object> map = new HashMap<>();
            ClassInfo classInfo = new ClassInfo();
            classInfo.setGradeId(grade.getId());
            List<ClassInfo> classInfoList = classInfoService.selectClassInfoList(classInfo);
            dateParamsHandler(query);

            List<Object> dataList = new ArrayList<>();
            List<String> classNameList = new ArrayList<>();
            for (ClassInfo info : classInfoList) {
                query.setClassId(info.getId());
                List<AdjustCourse> list = adjustCourseService.selectAdjustCourseList(query);
                int count = list.stream().mapToInt(a-> a.getCourseNo()).sum();
                Map<String,Object> dataValue = new HashMap<>();
                dataValue.put("value",count);
                dataValue.put("name",info.getClassName()+"班");
                dataList.add(count);
                classNameList.add(info.getClassName());

            }
            map.put("series",dataList);
            map.put("className",classNameList);
            map.put("grade",grade);
            mapList.add(map);
            logger.info("report result :"+ JSON.toJSONString(map));
        }
        logger.info("报表结果："+JSON.toJSONString(mapList));
        return mapList;
    }

    /**
     * 查询时间类型处理
     * @param query
     */
    private void dateParamsHandler(AdjustCourse query){
        Map<String, Object> params = query.getParams();

        Date bgDate = null,edDate = null;
        switch (query.getQueryType()){
            case 1:
                bgDate = DateUtils.getCurrentMonthStartTime();
                edDate = DateUtils.getCurrentMonthEndTime();
                break;
            case 2:
                bgDate = DateUtils.addMonths(new Date(),-6);
                edDate = new Date();
                break;
            default:
                bgDate = DateUtils.getCurrentWeekDayStartTime();
                edDate = DateUtils.getCurrentWeekDayEndTime();
                break;
        }
        params.put("beginTime",DateUtils.parseDateToStr(YYYY_MM_DD_HH_MM_SS,bgDate));
        params.put("endTime",DateUtils.parseDateToStr(YYYY_MM_DD_HH_MM_SS,edDate));
        query.setParams(params);
    }
    @RequiresPermissions("school:course:report")
    @GetMapping("/report")
    public String report()
    {
        return prefix + "/report";
    }
}
